package org.vectrics.common.html;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collection;
import java.util.Iterator;
import org.vectrics.SystemException;
import org.vectrics.common.util.FileUtil;
import org.vectrics.domain.Domain;
import org.vectrics.domain.HtmlCssEntry;
import org.vectrics.domain.HtmlFormType;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.VectricsTagSupport;


public class StyleSheetSectionTag extends VectricsTagSupport {
	private String form = null;
	
	public StyleSheetSectionTag() {
		super();
	}

	protected String makeStartTag() {
		Domain domain = ThreadProperties.getDomain();
		if (domain == null)
			throw new SystemException("Data Owner is null, form: " + form);
		
		String formCode = this.getForm();
		HtmlFormType formType = CoreServiceLocator.getSystemService().findHtmlFormType(formCode);
		
		String cachedHtml = findStyleSheetContent(domain, formType);
		if (cachedHtml == null) {
			throw new SystemException("Could not find style sheet for domain=" + domain
					+ "  FormType=" + formType);
		}
		return cachedHtml;
	}

	
	public void appendClassProperties(StringBuffer html, Collection propertyEntries) {
		Iterator iter = propertyEntries.iterator();
		if (iter.hasNext()) {
			boolean first = true;
			while (iter.hasNext()) {
				HtmlCssEntry entry = (HtmlCssEntry)iter.next();
				if (first) {
					html.append(entry.getClassName() + "{");
				}
				html.append(entry.getParameter() + ": " + entry.getValue());
				if (iter.hasNext()) {
					html.append("; ");
				}
				first = false;
			}
			html.append("}\r\n");
		}
		propertyEntries.clear();
	}
/*	
	public void saveHtmlToCache(String cachedHtml, Domain domain, HtmlFormType formType) {
		String fileName = formType.getCssFileName(domain);
		FileUtil.saveContentToFile(fileName, cachedHtml);
	}
*/	
	public String findStyleSheetContent(Domain domain, HtmlFormType formType) {
		URL url = null;
		URLConnection urlConnection = null;
		String cachedHtml = null;
		String fileName = formType.getCssFileName(domain);
		InputStream input =null;
		try {
			url = new URL(fileName);
			urlConnection = url.openConnection();
			input = urlConnection.getInputStream();
		} catch (MalformedURLException ex) {
			log.error("Mal Formada la URL: " + fileName, ex);
			throw new SystemException("Mal Formada la URL: " + fileName, ex);
		} catch (IOException ex) {
			log.error("Exception opening URL: " + fileName, ex);
			throw new SystemException("Exception opening file: " + fileName, ex);
		}
		StringBuffer str = new StringBuffer();
		try {
            int c;
            do {
                c = input.read();
                if (c != -1)
                    str.append((char)c);
            } while (c != -1);
            input.close();
        }
        catch (Exception ex) {
            str.append(ex.getMessage());
            log.error("Exception loading: " + fileName, ex);
        };
		cachedHtml = str.toString();
		if (cachedHtml.trim().length() == 0) {
				cachedHtml = null;
		} 
		return(cachedHtml);
	}
	
	
	
	/**
	 * @return Returns the form.
	 */
	public String getForm() {
		return form;
	}

	/**
	 * @param form The form to set.
	 */
	public void setForm(String form) {
		this.form = form;
	}
	
	
}
